{% extends 'home.html' %}
{% load staticfiles %}

{#修改样式#}
{% block style %}
    <style>
        #main-box {
            float: left;
            margin-top: 20px;
            margin-left: 25px;
            margin-bottom: 5px;

        }

        .btn {
            padding: 4px 8px;
            font-size: 12px;
        }

        #main-box {
            font-size: 12px;
        }

        #main-table {
            margin-top: 20px;
            font-size: 10px;
        }

        .warn, .ico {
            color: red;
        }

        #main-table, #main-table th {
            text-align: center;
        }

        table {
            table-layout: fixed; /* 必须这样td才能实现*/
        }

        table tr td {
            overflow: hidden; /* 内容超出宽度时隐藏超出部分的内容 */
            white-space: nowrap; /* 不换行 */
            text-overflow: ellipsis; /* 当对象内文本溢出时显示省略标记(...) ；需与overflow:hidden;一起使用*/
        }
    </style>
{% endblock style %}

{#编辑内容区#}
{% block contents %}

    {#按钮：新增、修改#}
    <div id="main-box">
        <div class="all-button">
            <span>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"
                        id="add">新增
                </button>
            </span>
            <span style="margin-left: 70px">
                <a href="/myTestFront/interfaceTest/download" class="btn btn-primary">模板下载</a>
            </span>
            <span>
                <label for="input-files" class="btn btn-primary">上传文件</label>
                <input type="file" name="test_files" id="input-files" style="width: 0;height: 0;display: inline-block">
            </span>
            <span>
                <button type="button" class="btn btn-primary" id="select-all">全选</button>
            </span>
            <span>
                <button type="button" class="btn btn-primary" id="start-test">开始测试</button>
            </span>
        </div>

        {# 新增弹出窗 #}
        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="exampleModalLabel">新增接口测试用例</h4>
                    </div>
                    <div class="modal-body">
                        <form id="add-edit-form">
                            <div id="cid" style="display: none"></div>
                            <div class="form-group">
                                <label for="req-url" class="ico">*</label>
                                <label for="req-url" class="control-label">请求地址:</label>
                                <label for="req-url" class="warn req-url"></label>
                                <input type="text" class="form-control" id="req-url" name="req_url"
                                       placeholder="必填">
                            </div>
                            <div class="form-group">
                                <label for="req-type" class="control-label">请求方式:</label>
                                <label for="req_type" class="warn"></label>
                                <select name="req_type" id="req-type" class="form-control">
                                    <option value="get">GET</option>
                                    <option value="post">POST</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="req-head" class="control-label">请求头:</label>
                                <label for="req-head" class="warn"></label>
                                <input type="text" class="form-control" id="req-head" name="req_head">
                            </div>
                            <div class="form-group">
                                <label for="req-body" class="control-label">请求体:</label>
                                <label for="req-body" class="warn"></label>
                                <textarea class="form-control" id="req-body" name="req_body"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="assert-type" class="control-label">断言方式:</label>
                                <label for="assert-type" class="warn"></label>
                                <select name="assert_type" id="assert-type" class="form-control">
                                    <option value="contain">包含</option>
                                    <option value="notcontain">不包含</option>
                                    <option value="equal">等于</option>
                                    <option value="notequal">不等于</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="assert-con" class="ico">*</label>
                                <label for="assert-con" class="control-label">断言内容:</label>
                                <label for="assert-con" class="warn"></label>
                                <textarea class="form-control" id="assert-con" name="assert_con"
                                          placeholder="必填"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="comment" class="control-label">备注:</label>
                                <label for="comment" class="warn"></label>
                                <textarea class="form-control" id="comment" name="comment"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" id="close">关闭</button>
                        <button type="button" class="btn btn-primary" id="submit">提交</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {# 删除弹窗#}
    {#    <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm">Small modal#}
    {#    </button>#}
    <div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content modal-footer delete-box">
                <div style="text-align: left; margin-bottom: 80px; font-weight: bold;">确认删除该测试用例吗？</div>
                <div class="delete-id" style="display: none"></div>
                <button type="button" class="btn btn-default" data-dismiss="modal" id="">取消</button>
                <button type="button" class="btn btn-primary" id="sure">确认</button>
            </div>
        </div>
    </div>

    {#    页面显示#}
    <div id="main-table">
        <table class="table table-striped">
            <thead>
            <tr>
                <th style="width: 7%">选中</th>
                <th style="width: 10%">创建者</th>
                <th style="width: 25%">请求地址</th>
                <th style="width: 10%">请求方式</th>
                <th>创建时间</th>
                <th style="width: 10%">测试结果</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for i in data %}
                <tr>
                    <td><input type="checkbox"  name="select-id" value="{{ i.id }}" class="selected"></td>
                    <td>{{ i.create_user }}</td>
                    <td title="{{ i.req_url }}" style="cursor: pointer">{{ i.req_url }}</td>
                    <td>{{ i.req_type | upper }}</td>
                    <td>{{ i.creat_time | date:"Y-m-d H:i:s" }}</td>
                    <td class="test-result" style="text-transform:capitalize">{{ i.test_cur_res }}</td>
                    <td>
                        <a class="edit" data-toggle="modal" data-target="#exampleModal" href="#"
                           val="{{ i.id }}">修改</a>
                        |
                        <a class="delete" data-toggle="modal" data-target=".bs-example-modal-sm" href="#"
                           val="{{ i.id }}">删除</a>
                        |
                        <a class="start-test" href="#" val="{{ i.id }}">开始测试</a>
                        |
                        <a class="look" href="#" data-toggle="modal" data-target=".bs-example-modal-lg"
                           val="{{ i.id }}">查看</a>
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

    {#    查看分页标签#}
    <!-- Large modal -->
    {#    <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large modal#}
    {#    </button>#}
    <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content" style="font-size:10px ">
                <div>
                    <!-- Nav tabs -->
                    <ul class="nav nav-tabs" role="tablist">
                        <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab"
                                                                  data-toggle="tab">请求内容</a></li>
                        <li role="presentation"><a href="#profile" aria-controls="profile" role="tab"
                                                   data-toggle="tab">测试记录</a>
                        </li>
                        {#                        <li role="presentation"><a href="#messages" aria-controls="messages" role="tab"#}
                        {#                                                   data-toggle="tab">拓展页</a></li>#}

                    </ul>

                    <!-- Tab panes -->
                    <div class="tab-content">
                        <div role="tabpanel" class="tab-pane active" id="home">
                            <div class="modal-body">
                                <form>
                                    <div id="cid1" style="display: none"></div>
                                    <div class="form-group">
                                        <label for="req-url" class="control-label">请求地址:</label>
                                        <input type="text" class="form-control" id="req-url1" name="req_url"
                                               placeholder="必填">
                                    </div>
                                    <div class="form-group">
                                        <label for="req-type" class="control-label">请求方式:</label>
                                        <select name="req_type" id="req-type1" class="form-control">
                                            <option value="get">GET</option>
                                            <option value="post">POST</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="req-head" class="control-label">请求头:</label>
                                        <input type="text" class="form-control" id="req-head1" name="req_head">
                                    </div>
                                    <div class="form-group">
                                        <label for="req-body" class="control-label">请求体:</label>
                                        <textarea class="form-control" id="req-body1" name="req_body"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="assert-type" class="control-label">断言方式:</label>
                                        <select name="assert_type" id="assert-type1" class="form-control">
                                            <option value="contain">包含</option>
                                            <option value="notcontain">不包含</option>
                                            <option value="equal">等于</option>
                                            <option value="notequal">不等于</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="assert-con" class="control-label">断言内容:</label>
                                        <textarea class="form-control" id="assert-con1" name="assert_con"
                                                  placeholder="必填"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="comment" class="control-label">备注:</label>
                                        <textarea class="form-control" id="comment1" name="comment"></textarea>
                                    </div>
                                </form>
                            </div>
                        </div>
                        {#                        测试记录#}
                        <div role="tabpanel" class="tab-pane" id="profile">
                            <div class="modal-body">
                                <table class="table table-bordered">
                                    <thead>
                                    <tr>
                                        <th>请求方式</th>
                                        <th style="width: 60%">响应内容</th>
                                        <th>请求结果</th>
                                        <th style="width: 20%">测试时间</th>
                                    </tr>
                                    </thead>
                                    <tbody class="test-record">
                                    {#自动生成记录#}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    {#                        <div role="tabpanel" class="tab-pane" id="messages">拓展内容</div>#}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    {#    分页显示#}
    <ul class="pagination pagination-sm" style="position: fixed;right: 2%;bottom: 0%">
        {{ page_obj.page_html | safe }}
    </ul>

{% endblock %}

{#js部分#}
{% block script %}
    <script src="{% static 'plugins/bootstrap/js/bootstrap.js' %}"></script>
    <script>
        // 输入焦点清除必填提醒
        $('.form-control').focusin(function () {
            $(this).prev().text('')
        });

        // 添加必填提醒
        $('[placeholder="必填"]').focusout(function () {
            if ($(this).val() == '') {
                $(this).prev().text('必填')
            }
        });

        // 当鼠标放到提交按钮时检测必填项
        $('#submit').mouseover(function () {
            $('[placeholder="必填"]').each(function () {
                if ($(this).val() == '') {
                    $(this).prev().text('必填')
                }
            })
        });

        // ajax提交新增和修改内容
        $('#submit').click(function () {
            var formData = $('#add-edit-form').serializeArray();     // 获取form表单里的内容
            var jsonObj = {};
            for (var i in formData) {
                jsonObj[formData[i].name] = formData[i].value
            }
            console.log(jsonObj)
            // 通过判断cid有无值进行判断是新增还是修改
            if ($('#cid').text() == '') {
                $.post(
                    '{% url 'interfaceTest' %}',
                    jsonObj,
                    function (response) {
                        {#console.log(response);#}
                        if (response == 'success') {
                            $('#exampleModal').modal('hide');   // 响应后关闭弹窗}
                            window.location.reload()
                        } else {
                            console.log(response);
                            $('.req-url').text('请输入有效的地址')

                        }
                    })
            } else {
                jsonObj['id'] = $('#cid').text();    // 通过这个id进行修改内容
                {#console.log(jsonObj);#}
                $.post(
                    '{% url 'interfaceTestChange' %}',
                    jsonObj,
                    function (response) {
                        {#console.log(response);#}
                        if (response == 'success') {
                            $('#exampleModal').modal('hide');   // 响应后关闭弹窗}
                            window.location.reload()
                        } else {
                            console.log(response);
                            $('.req-url').text('请输入有效的地址')
                        }
                    })
            }
        });

        // 点击新增关闭时页面刷新
        {#$('#close').click(function () {#}
        {#    window.location.reload()#}
        //{#});#}

        // 点击全选按钮
        var flag = false;
        $('#select-all').click(function () {
            var checks = $('input[type=checkbox]');
            if(flag){
                for(var i = 0;i<checks.length;i++){
                    $(checks[i]).prop('checked', false);
                    $(checks[i]).attr('checked', false)
                }
                flag = false
            }else {
                for(var i = 0;i<checks.length;i++){
                    $(checks[i]).prop('checked', true);
                    $(checks[i]).attr('checked', true)
                }
                flag = true
            }
        });

        // 单选按钮
        $('.selected').click(function () {
            console.log($(this).prop('checked'))
            if($(this).prop('checked')){
               $(this).prop('checked', true);
                $(this).attr('checked', true)
            }
            else {
                $(this).prop('checked', false);
                $(this).attr('checked', false)
            }
        });

        // 点击删除后，
        $('.delete').click(function () {
            $('.delete-id').text($(this).attr('val'));

        });
        // 点击弹窗确认删除
        $('#sure').click(function () {
            console.log($('.delete-id').text());
            $.get(
                '{% url 'interfaceTestDelete' %}',
                {id: $('.delete-id').text()},
                function (response) {
                    window.location.reload()
                }
            )
        });

        // 点击修改获取之前的数据并回填
        $('.edit').click(function () {
            $.getJSON(
                '{% url 'interfaceTestChange' %}',
                {id: $(this).attr('val')},
                function (response) {
                    $('#cid').text(response.id);
                    $('#req-url').val(response.req_url);
                    $('#req-type').val(response.req_type);
                    $('#req-head').val(response.req_head);
                    $('#req-body').val(response.req_body);
                    $('#assert-type').val(response.assert_type);
                    $('#assert-con').val(response.assert_con);
                    $('#comment').val(response.comment);
                }
            )

        });

        // 点击查看，请求内容回显
        $('.look').click(function () {
            $.getJSON(
                '{% url 'getTestRecord' %}',
                {id: $(this).attr('val'), look_id: 1},      // look_id 为1--查看请求内容， 2--测试记录
                function (response) {
                    $('#cid1').text(response.id);
                    $('#req-url1').val(response.req_url);
                    $('#req-type1').val(response.req_type);
                    $('#req-head1').val(response.req_head);
                    $('#req-body1').val(response.req_body);
                    $('#assert-type1').val(response.assert_type);
                    $('#assert-con1').val(response.assert_con);
                    $('#comment1').val(response.comment);
                    $('.tab-content input, .tab-content textarea, .tab-content select').attr('disabled', true);    // 设置禁止修改disable

                    // 获取测试记录
                    $.getJSON(
                        '{% url 'getTestRecord' %}',
                        {id: $('#cid1').text(), look_id: 2},     // look_id 为1--查看请求内容， 2--测试记录
                        function (response_data) {
                            console.log(response_data);
                            $('.test-record').empty();    // 将动态生成的内容进行清除
                            for (var j = 0; j < response_data.length; j++) {
                                var trTemp = $('<tr></tr>');
                                trTemp.append('<td>' + response_data[j].test_type + '</td>');
                                trTemp.append('<td class="test-response" title="">' + response_data[j].test_response + '</td>');
                                if (response_data[j].test_res == 'fail') {
                                    trTemp.append('<td style="color:red;">' + response_data[j].test_res + '</td>');
                                } else {
                                    trTemp.append('<td>' + response_data[j].test_res + '</td>');
                                }
                                trTemp.append('<td>' + response_data[j].test_time + '</td>');
                                trTemp.appendTo('.test-record');
                                // 查看记录时，给响应内容绑定事件
                                $('.test-response').hover(function () {
                                    $(this).css('cursor', 'pointer');    // 设置手型
                                    $(this).attr('title', $(this).text())
                                });
                            }
                        }
                    );
                }
            )
        });

        // 执行测试
        $('.start-test').click(function () {
            var start_test = $(this);
            start_test .css('color', 'red').attr('disabled', true).css("pointer-events","none").text('测试执行中');
            $.getJSON(
                '{% url 'doInterfaceTest' %}',
                {id: start_test.attr('val')},
                function (response) {
                    console.log(response);
                    start_test.parent().prev().text(response.test_result);
                    // 当响应结果为fail时修改测试结果字体颜色
                    if (response.test_result == 'fail') {
                        start_test.parent().prev().css('color', 'red')
                    } else {
                        start_test.parent().prev().css('color', 'green')
                    }
                    start_test.css('color', '#337ab7').attr('disabled', false).css("pointer-events","auto").text('开始测试');
                }
            );

        });

        // 多选执行测试
        $('#start-test').click(function () {
            $('#start-test').css('color', 'red').attr('disabled', true).text('测试执行中');     // 设置按钮内容
            var data = [];
            $('.selected').each(function (index, ele) {
                if ($(this).attr('checked')) {    // 如果input标签被选
                    data.push($(this).val())
                }
            });
            console.log(data);
            $.ajax({
                url: '{% url 'doManyInterfaceTest' %}',
                type: 'POST',
                data: {id: JSON.stringify(data)},
                success: function (response) {
                    console.log(response);
                    console.log(JSON.parse(response).test_result[0]);
                    let test_result = JSON.parse(response).test_result[0];
                    $.each(data, function (index, ele) {
                        $('.selected').each(function () {
                            if ($(this).val() == ele) {
                                if (test_result[ele] == 'fail') {
                                    $(this).parent().siblings('.test-result').css('color', 'red')
                                } else {
                                    $(this).parent().siblings('.test-result').css('color', 'green')
                                }
                                $(this).parent().siblings('.test-result').text(test_result[ele])
                            }
                        })
                    });
                    $('#start-test').css('color', 'white').text('开始测试').attr('disabled', false);     // 设置按钮内容
                }
            })
        });

        // 页面初始化的时候标记fail、pass的字体颜色
        $(document).ready(function () {
            $('tr').each(function () {
                if ($(this).children('.test-result').text() == 'fail') {
                    $(this).children('.test-result').css('color', 'red')
                } else {
                    $(this).children('.test-result').css('color', 'green')
                }
            })
        });

        // 上传文件
        $('#input-files').change(function () {
            var files = $(this).prop('files');      // 获取文件
            console.log(files);
            var data = new FormData();
            data.append('test_files', files[0]);
            $.ajax({
                url: '{% url 'upload' %}',
                type: 'POST',
                data: data,
                dataType: 'json',
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    window.location.reload();

                },
                error: function (response) {
                    console.log(response);
                    alert('只能上传格式为xls、xlsx')
                }
            })
        })


    </script>
{% endblock script %}